package com.mooc.lib_common.mvvm

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import com.mooc.lib_base_application.BaseApplication
import org.koin.androidx.viewmodel.ext.android.getViewModel
import kotlin.reflect.KClass

abstract class BaseFragment<VM : ViewModel,V : ViewDataBinding> : Fragment(){

    protected lateinit var vm : VM
    protected lateinit var v : V

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        BaseApplication.instance!!.ref.watch(this)
        v = DataBindingUtil.inflate(inflater,bindLayout(),container,false)
        initView()
        initViewModel()
        initData()
        return v.root
    }

    //创建ViewModel对象
    fun initViewModel(){
        val clazz =
            this.javaClass.kotlin.supertypes[0].arguments[0].type!!.classifier!! as KClass<VM>
        vm = getViewModel<VM>(clazz) //koin 注入
    }

    //初始化控件
    abstract fun initView()
    //创建databinding对象
    abstract fun bindLayout():Int
    //初始化数据
    abstract fun initData()

    override fun onDestroy() {
        super.onDestroy()
        v.unbind()
    }

}